package day17.tarena.com.gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.*;
public class MyComputer implements ActionListener{
	private boolean append = false;//append��ʾ����״̬(׷��/�滻)
	JTextField jtf = new JTextField(10);
	private String op1 = "0";
	private String operator = "+";
	public void actionPerformed(ActionEvent ae){
		String comm = ae.getActionCommand();
		//if("0".equals(comm)||"1".equals(comm))
		//if(comm.matches("^\\d+$"))
		if("0123456789".indexOf(comm)!=-1){
			if(append){//׷��
				String temp  = jtf.getText();
				jtf.setText(temp+comm);
			}else{//�滻
				jtf.setText(comm);
				append = true;
			}
		}else if("+-*/".indexOf(comm)!=-1){
			op1 = jtf.getText();
			operator = comm;
			append = false;
		}else if("=".equals(comm)){
			String op2 = jtf.getText();
			double d1 = Double.parseDouble(op1);
			double d2 = Double.parseDouble(op2);
			if("+".equals(operator)){
				d1 = d1 + d2;
			}else if("-".equals(operator)){
				d1 = d1 - d2;
			}else if("*".equals(operator)){
				d1 = d1 * d2;
			}else{
				d1 = d1 / d2;
			}
			jtf.setText(d1+"");
			append = false;
		}else if(".".equals(comm)){
			String temp = jtf.getText();
			if(temp.indexOf(".")==-1){//û��С���
				jtf.setText(temp+".");
				append = true;
			}
		}else if("+/-".equals(comm)){
			String temp = jtf.getText();
			if(temp.startsWith("-")){
				jtf.setText(temp.substring(1));
			}else{
				jtf.setText("-"+temp);
			}
		}else if("BackS".equals(comm)){
			String temp = jtf.getText();
			if(temp.length()>0){
				jtf.setText(temp.substring(0,temp.length()-1));
			}
		}else if("CE".equals(comm)||"C".equals(comm)){
			jtf.setText("0");
			append = false;
		}
	}
	public MyComputer(){
		JFrame jf = new JFrame("MyComputer");
		jf.add(jtf,BorderLayout.NORTH);
		JPanel jp = new JPanel();
		GridLayout gl = new GridLayout(5,4);
		String[] lab = {"BackS","CE","C","+",
			"7","8","9","-","4","5","6","*",
			"1","2","3","/","0","+/-",".","="};
		jp.setLayout(gl);
		for(int i=0;i<lab.length;i++){
			JButton jb = new JButton(lab[i]);
			jp.add(jb);
			jb.addActionListener(this);
		}
		jtf.setEditable(false);//�����ı��򲻿ɱ༭
		jf.add(jp);
		jf.setLocation(300,200);//���ó���λ��
		//jf.setSize(300,200);//���ô�С
		jf.pack();//�Զ�����ڴ�С
		jf.setResizable(false);//���ô��ڴ�С���ɸı�
		jf.setVisible(true);//���ÿɼ�
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		new MyComputer();
	}
}
